﻿using System.Collections.ObjectModel;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Windows;
using MeterReader.WPF.Common.Extensions;
using MeterReader.WPF.Models;
using Microsoft.EntityFrameworkCore;

namespace MeterReader.WPF.Services
{
    public class ReadSimDataService : IReadData
    {
        private readonly SimDbContext _context;
        private readonly ISaveData _saveData;
        private readonly IDialogService _dialogService;
        private CancellationTokenSource _cancellationTokenSource = new();
        private readonly ObservableCollection<MeterDataCollection> _collection = new();
        private int _num = 0;
        private bool _isWorking = false;
        public bool IsWorking => _isWorking;

        public event EventHandler? WorkStatusChanged;

        public ObservableCollection<MeterDataCollection> GetMeterDataCollections() => _collection;

        public ReadSimDataService(SimDbContext context, ISaveData saveData, IDialogService dialogService)
        {
            _context = context;
            _saveData = saveData;
            _dialogService = dialogService;
        }

        public async Task StartRead()
        {
            OnWorkStatusChanged(true);
            await Task.Delay(1);
            try
            {
                while (!_cancellationTokenSource.Token.IsCancellationRequested)
                {
                    // 读取数据
                    var meter =
                        await _context.TMeters.OrderBy(t => t.Id).Skip(_num - 1).FirstOrDefaultAsync(_cancellationTokenSource.Token) ?? new TMeter();
                    _num++;
                    _collection.AddNewMeterDataCollection(meter);
                    // 写入数据库 ,发送http
                    await _saveData.PostDataAsync("https://localhost:7121/SaveData", meter);
                    // 等待 1 秒钟
                    await Task.Delay(1000, _cancellationTokenSource.Token);
                }
            }
            catch (OperationCanceledException ex)
            {
                _cancellationTokenSource = new CancellationTokenSource();
				ShowMsgDialog(ex.Message);
            }
            catch (TimeoutException ex)
            {
                StopRead();
                _cancellationTokenSource = new CancellationTokenSource();
                string message = $"读取数据超时：{this.GetType().FullName}：{ex.Message}{Environment.NewLine}Inner Exception: {ex.InnerException?.Message}";
				ShowMsgDialog(message);
			}
			catch (Exception ex)
            {
                StopRead();
                _cancellationTokenSource = new CancellationTokenSource();
                string message = $"读取数据异常：{this.GetType().FullName}：{ex.Message}{Environment.NewLine}Inner Exception: {ex.InnerException?.Message}";
				ShowMsgDialog(message);

			}
		}

        public void StopRead()
        {
            _cancellationTokenSource.Cancel();
            OnWorkStatusChanged(false);
        }

        protected virtual void OnWorkStatusChanged(bool status)
        {
            _isWorking = status;
            WorkStatusChanged?.Invoke(this, EventArgs.Empty);
        }


        private void ShowMsgDialog(string msg)
        {
			DialogParameters paras = new DialogParameters();
			paras.Add("fault", msg);
			_dialogService.ShowDialog("Message",paras);
		}
	}
}
